package com.farm.project.service.impl;

import com.farm.project.domain.ActiveAttr;
import com.farm.project.domain.Project;
import com.farm.project.domain.ProjectActive;
import com.farm.project.domain.Tasklink;
import com.farm.project.domain.Tasknode;
import com.farm.project.domain.ex.EchartsTaskData;
import com.farm.project.domain.ex.EchartsTaskLink;
import com.farm.project.domain.ex.EchartsTaskNode;
import com.farm.project.domain.ex.EchartsTaskNodeStyle;
import com.farm.project.domain.ex.FlowModel;
import com.farm.project.domain.ex.TaskAppModel;
import com.farm.core.time.TimeTool;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.farm.project.dao.ActiveattrDaoInter;
import com.farm.project.dao.ProjectDaoInter;
import com.farm.project.dao.ProjectactiveDaoInter;
import com.farm.project.dao.TasklinkDaoInter;
import com.farm.project.dao.TasknodeDaoInter;
import com.farm.project.service.ProjectServiceInter;
import com.farm.project.service.TasklinkServiceInter;
import com.farm.project.service.TasknodeServiceInter;
import com.farm.template.dao.TemplateDaoInter;
import com.farm.template.dao.TemplatedirDaoInter;
import com.farm.template.dao.TemplatefileDaoInter;
import com.farm.template.domain.Template;
import com.farm.template.domain.TemplateDir;
import com.farm.template.domain.TemplateFile;
import com.farm.template.service.TemplateServiceInter;
import com.farm.template.utils.FarmJsonUtils;
import com.farm.template.utils.FarmStringUtils;
import com.farm.template.utils.Formulas;
import com.farm.web.WebUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.farm.core.sql.query.DBRule;
import com.farm.core.sql.query.DBRuleList;
import com.farm.core.sql.query.DataQuery;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.Resource;

import com.farm.configer.dao.ConfigerDaoInter;
import com.farm.configer.dao.ConfigerformDaoInter;
import com.farm.configer.domain.Configer;
import com.farm.configer.domain.Configerform;
import com.farm.configer.domain.ex.ConfigerMetaPara;
import com.farm.configer.form.FormModelUtils;
import com.farm.configer.service.ConfigerServiceInter;
import com.farm.core.auth.domain.LoginUser;

/* *
 *功能：工程项目服务层实现类
 *详细：
 *
 *版本：v0.1
 *作者：FarmCode代码工程
 *日期：20150707114057
 *说明：
 */
@Service
public class ProjectServiceImpl implements ProjectServiceInter {
	@Resource
	private ProjectDaoInter projectDaoImpl;
	@Resource
	private TasknodeDaoInter tasknodeDaoImpl;
	@Resource
	private TasklinkDaoInter tasklinkDaoImpl;
	@Resource
	private TemplateServiceInter templateServiceImpl;
	@Resource
	private TasknodeServiceInter taskNodeServiceImpl;
	@Resource
	private TasklinkServiceInter taskLinkServiceImpl;
	@Resource
	private ConfigerServiceInter configerServiceImpl;
	@Resource
	private ActiveattrDaoInter activeattrDaoImpl;
	@Resource
	private ProjectactiveDaoInter projectactiveDaoImpl;
	@Resource
	private TemplateDaoInter templateDaoImpl;
	@Resource
	private TemplatedirDaoInter templatedirDaoImpl;
	@Resource
	private TemplatefileDaoInter templatefileDaoImpl;
	@Resource
	private ConfigerformDaoInter configerformDaoImpl;
	@Resource
	private ConfigerDaoInter configerDaoImpl;
	private static final Logger log = Logger.getLogger(ProjectServiceImpl.class);

	@Override
	@Transactional
	public Project insertProjectEntity(Project entity, LoginUser user) {
		entity.setCuser(user.getId());
		entity.setCtime(TimeTool.getTimeDate14());
		entity.setEuser(user.getId());
		entity.setEtime(TimeTool.getTimeDate14());
		return projectDaoImpl.insertEntity(entity);
	}

	@Override
	@Transactional
	public Project editProjectEntity(Project entity, LoginUser user) {
		Project entity2 = projectDaoImpl.getEntity(entity.getId());
		entity2.setEuser(user.getId());
		entity2.setEtime(TimeTool.getTimeDate14());
		// entity2.setCatalogid(entity.getCatalogid());
		entity2.setName(entity.getName());
		entity2.setPcontent(entity.getPcontent());
		entity2.setPstate(entity.getPstate());
		projectDaoImpl.editEntity(entity2);
		return entity2;
	}

	@Override
	@Transactional
	public void deleteProjectEntity(String id, LoginUser user) {
		DBRuleList dbs = DBRuleList.getInstance().add(new DBRule("projectid", id, "="));
		tasknodeDaoImpl.deleteEntitys(dbs.toList());
		tasklinkDaoImpl.deleteEntitys(dbs.toList());
		activeattrDaoImpl.deleteEntitys(dbs.toList());
		projectactiveDaoImpl.deleteEntitys(dbs.toList());
		projectDaoImpl.deleteEntity(projectDaoImpl.getEntity(id));
	}

	@Override
	@Transactional
	public Project getProjectEntity(String id) {
		// TODO 自动生成代码,修改后请去除本注释
		if (id == null) {
			return null;
		}
		return projectDaoImpl.getEntity(id);
	}

	@Override
	@Transactional
	public DataQuery createProjectSimpleQuery(DataQuery query) {
		// TODO 自动生成代码,修改后请去除本注释
		DataQuery dbQuery = DataQuery.init(query, "CBTG_PROJECT A LEFT JOIN CBTG_APP_CATALOG B ON B.ID=A.CATALOGID",
				"A.ID AS ID,A.CATALOGID AS CATALOGID,A.NAME AS NAME,A.PCONTENT AS PCONTENT,A.PSTATE AS PSTATE,A.EUSER AS EUSER,B.NAME as CATALOGNAME,A.CTIME AS CTIME,A.ETIME AS ETIME,A.CUSER AS CUSER");
		return dbQuery;
	}

	@Override
	@Transactional
	public void updateCatalog(String tids, String catalogId, LoginUser currentUser) {
		for (String templateId : WebUtils.parseIds(tids)) {
			Project temp = projectDaoImpl.getEntity(templateId);
			temp.setCatalogid(catalogId);
			projectDaoImpl.editEntity(temp);
		}
	}

	@Override
	@Transactional
	public EchartsTaskData getDatas(String projectId) {
		EchartsTaskData data = new EchartsTaskData();
		data.getNodes().add(new EchartsTaskNode("START", "开始", 10, 300, new EchartsTaskNodeStyle("#666666")));
		int n = 1;
		Map<String, EchartsTaskNode> dic = new LinkedHashMap<String, EchartsTaskNode>();
		for (Tasknode node : tasknodeDaoImpl
				.selectEntitys(DBRuleList.getInstance().add(new DBRule("PROJECTID", projectId, "=")).toList())) {

			String name = "未绑定业务";
			String color = "#666666";
			if (node.getModel().equals("configer")) {
				Configer configer = configerServiceImpl.getConfigerEntity(node.getRid());
				if (configer != null) {
					name = configer.getName();
				}
				color = "#b23f59";
			}
			if (node.getModel().equals("template")) {
				Template template = templateServiceImpl.getTemplateEntity(node.getRid());
				if (template != null) {
					name = template.getName();
				}
				color = "#206b66";
			}

			EchartsTaskNode enode = new EchartsTaskNode(node.getId(), name, 10 + (n * 10), 300,
					new EchartsTaskNodeStyle(color));
			dic.put(enode.getName(), enode);
			data.getNodes().add(enode);
			n++;
		}
		for (Tasklink node : tasklinkDaoImpl
				.selectEntitys(DBRuleList.getInstance().add(new DBRule("PROJECTID", projectId, "=")).toList())) {
			String content = node.getPcontent();
			if (StringUtils.isBlank(content)) {
				if (!node.getExpression().equals("false")) {
					content = node.getExpression();
				}
			}
			if (content != null && content.length() > 32) {
				content = content.substring(0, 29) + "...";
			}
			data.getLinks().add(new EchartsTaskLink(node.getSnodeid(), node.getTnodeid(), content));
		}

		EchartsTaskNode endNode = new EchartsTaskNode("END", "结束", 10 + (n * 10), 300,
				new EchartsTaskNodeStyle("#666666"));

		data.getNodes().add(endNode);
		if (data.getNodes().size() == 2) {
			data.getLinks().add(new EchartsTaskLink("START", "END"));
		}

		int level = 1;
		int max = 0;
		// 每个leve中的全部节点
		List<EchartsTaskNode> tasks = new ArrayList<EchartsTaskNode>();

		tasks.add(new EchartsTaskNode("START", "START", 0, 0, null));

		while (true) {
			List<EchartsTaskNode> lasttasks = new ArrayList<EchartsTaskNode>();
			for (EchartsTaskNode node : tasks) {
				// 当前任务
				String sid = node.getName();
				for (EchartsTaskLink link : data.getLinks()) {
					if (sid.equals(link.getSource())) {
						// 下一层任务列表
						EchartsTaskNode cnode = dic.get(link.getTarget());
						if (cnode != null) {
							cnode.setX(10 + (level * 10));
							lasttasks.add(cnode);
						}
					}
				}

			}
			level++;
			max++;
			tasks = lasttasks;
			// 計算高度
			{
				int all = lasttasks.size();

				int min = 300 + (level * 5);

				if (all > 1) {
					if (level % 2 == 0) {
						min = 300 + (level % 2 * 2);
					} else {
						min = 300 - (level % 2 * 2);
					}
				} else {
					min = 300;
				}

				if (all > 1) {
					min = min - (all - 1) * 10 / 2;
				}
				int num = 0;
				for (EchartsTaskNode node : lasttasks) {
					node.setY(min + (num * 10));
					num++;
				}
			}

			if (max >= 100 || tasks.size() <= 0) {
				break;
			}
		}
		endNode.setX(10 + ((level - 1) * 10));
		return data;
	}

	@Override
	@Transactional
	public void deleteAllTasknode(String projectId, LoginUser currentUser) {
		DBRuleList dbs = DBRuleList.getInstance().add(new DBRule("projectid", projectId, "="));
		tasknodeDaoImpl.deleteEntitys(dbs.toList());
		tasklinkDaoImpl.deleteEntitys(dbs.toList());
	}

	@Override
	@Transactional
	public List<Project> getPublicProjects() {
		// 1:创建,2:发布,0:禁用
		return projectDaoImpl.selectEntitys(DBRuleList.getInstance().add(new DBRule("PSTATE", "2", "=")).toList());
	}

	@Override
	@Transactional
	public List<ProjectActive> getAllActive(String projectid) {
		return projectactiveDaoImpl
				.selectEntitys(DBRuleList.getInstance().add(new DBRule("PROJECTID", projectid, "=")).toList());
	}

	@Override
	@Transactional
	public ProjectActive creatActive(String projectid, String note, LoginUser currentUser) {

		ProjectActive active = new ProjectActive();
		active.setCtime(TimeTool.getTimeDate14());
		active.setCuser(currentUser.getId());
		active.setEtime(TimeTool.getTimeDate14());
		active.setEuser(currentUser.getId());
		active.setNodeid("START");
		active.setPcontent(note);
		active.setProjectid(projectid);
		active.setPstate("1");
		active = projectactiveDaoImpl.insertEntity(active);

		return active;
	}

	@Override
	@Transactional
	public ProjectActive getActive(String activeid) {
		return projectactiveDaoImpl.getEntity(activeid);
	}

	@Override
	@Transactional
	public void toDoNextTaskNode(String activeid) {
		ProjectActive active = projectactiveDaoImpl.getEntity(activeid);
		List<Tasklink> links = tasklinkDaoImpl
				.selectEntitys(DBRuleList.getInstance().add(new DBRule("PROJECTID", active.getProjectid(), "="))
						.add(new DBRule("SNODEID", active.getNodeid(), "=")).toList());
		if (links.size() < 1) {
			throw new RuntimeException(
					"当前任务的下级任务为0,projectid:" + active.getProjectid() + ",taskNodeId:" + active.getNodeid());
		}
		Tasklink link = null;
		Map<String, Object> debugLogs = new HashMap<String, Object>();
		{// 计算下一个节点
			for (Tasklink clink : links) {
				String result = "false";
				Map<String, Object> log = new HashMap<String, Object>();
				log.put("条件表达式：", clink.getExpression());
				log.put("备注", clink.getPcontent());
				try {
					String expression = clink.getExpression();
					Map<String, Object> paras = getActiveConfigerMap(activeid);
					result = Formulas.executeFormula(expression, paras);
					log.put("运行结果：", result);
				} catch (Exception e) {
					log.put("运行结果：", e.getMessage());
					result = "false";
				}
				debugLogs.put(clink.getTnodeid(), log);
				if (result.equals("true")) {
					link = clink;
					break;
				}
			}
		}
		if (link == null) {
			link = links.get(0);
		}
		active.setNodeid(link.getTnodeid());
		active.setLogjson(FarmJsonUtils.toJson(debugLogs));
		projectactiveDaoImpl.editEntity(active);
	}

	@Override
	@Transactional
	public void chooseActiveNode(String activeid, String nodeid, LoginUser currentUser) {
		ProjectActive active = projectactiveDaoImpl.getEntity(activeid);

		List<Tasklink> links1 = tasklinkDaoImpl
				.selectEntitys(DBRuleList.getInstance().add(new DBRule("SNODEID", nodeid, "="))
						.add(new DBRule("PROJECTID", active.getProjectid(), "=")).toList());

		List<Tasklink> links2 = tasklinkDaoImpl
				.selectEntitys(DBRuleList.getInstance().add(new DBRule("TNODEID", nodeid, "="))
						.add(new DBRule("PROJECTID", active.getProjectid(), "=")).toList());

		if (links1.size() + links2.size() > 0) {
			active.setNodeid(nodeid);
			projectactiveDaoImpl.editEntity(active);
		} else {
			throw new RuntimeException("指定任务NODEID不存在,nodeId:" + nodeid);

		}

	}

	@Override
	@Transactional
	public void saveActiveParameters(String activeid, String key, String val, LoginUser currentUser) {
		ProjectActive active = projectactiveDaoImpl.getEntity(activeid);
		activeattrDaoImpl
				.deleteEntitys(DBRuleList.getInstance().add(new DBRule("PROJECTID", active.getProjectid(), "="))
						.add(new DBRule("ACTIVEID", active.getId(), "=")).add(new DBRule("CODE", key, "=")).toList());
		ActiveAttr aa = new ActiveAttr();
		aa.setActiveid(activeid);
		aa.setCode(key);
		aa.setCtime(TimeTool.getTimeDate14());
		aa.setCuser(currentUser.getId());
		aa.setEtime(TimeTool.getTimeDate14());
		aa.setEuser(currentUser.getId());
		// aa.setPcontent(val);
		aa.setProjectid(active.getProjectid());
		aa.setPstate("1");
		aa.setVal(val);
		activeattrDaoImpl.insertEntity(aa);
	}

	@Override
	@Transactional
	public List<ConfigerMetaPara> getActiveConfigers(String activeid) {
		List<ActiveAttr> attrs = activeattrDaoImpl
				.selectEntitys(DBRuleList.getInstance().add(new DBRule("ACTIVEID", activeid, "=")).toList());
		List<ConfigerMetaPara> list = new ArrayList<ConfigerMetaPara>();
		for (ActiveAttr attr : attrs) {
			ConfigerMetaPara para = new ConfigerMetaPara();
			para.setCode(attr.getCode());
			para.setJsonString(attr.getVal());
			list.add(para);
		}
		return list;
	}

	@Override
	@Transactional
	public Map<String, Object> getActiveConfigerMap(String activeid) {
		Map<String, Object> configerMap = new HashMap<String, Object>();
		for (ConfigerMetaPara node : getActiveConfigers(activeid)) {
			configerMap.put(node.getCode(), FormModelUtils.jsonStrToObjects(node.getJsonString()));
		}
		return configerMap;
	}

	@Override
	@Transactional
	public void delActive(String activeid) {
		activeattrDaoImpl.deleteEntitys(DBRuleList.getInstance().add(new DBRule("ACTIVEID", activeid, "=")).toList());
		projectactiveDaoImpl.deleteEntity(projectactiveDaoImpl.getEntity(activeid));

	}

	@Override
	@Transactional
	public List<String> getActiveTemplateMarkMap(String activeid) {
		Map<String, Object> parss = getActiveConfigerMap(activeid);
		List<String> marks = getActiveTemplateMarkMap_filter(parss, "", new ArrayList<String>());
		return marks;
	}

	/**
	 * 递归扫描所有变量的上下级关系并返回层级表示的list（配合 getActiveTemplateMarkMap方法使用）
	 * 
	 * @param node 参数集合
	 * @param path 上级路径
	 * @param list 模板元素集合
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private List<String> getActiveTemplateMarkMap_filter(Object obj, String path, List<String> list) {
		if (obj instanceof Map) {
			Map<String, Object> map = (Map<String, Object>) obj;
			for (Entry<String, Object> node : map.entrySet()) {
				String cpath = "";
				if (StringUtils.isBlank(path)) {
					cpath = node.getKey();
				} else {
					cpath = path + "." + node.getKey();
				}
				getActiveTemplateMarkMap_filter(node.getValue(), cpath, list);
			}
		} else {
			if (obj instanceof List) {
				List<Map<String, Object>> objs = (List<Map<String, Object>>) obj;
				int n = 0;
				for (Map<String, Object> node : objs) {
					String cpath = path + "[" + (n++) + "]";
					getActiveTemplateMarkMap_filter(node, cpath, list);
				}
			} else {
				if (obj instanceof String) {
					if (obj.toString().length() > 20) {
						obj = obj.toString().substring(0, 15) + "...";
					}
				}
				list.add(("${" + path + "!}" + "=" + obj));
			}
		}
		return list;
	}

	@Override
	@Transactional
	public String getProjectJson(String projectid) {
		Map<String, Object> json = new HashMap<String, Object>();
		Project project = getProjectEntity(projectid);
		List<Tasknode> tasknodes = tasknodeDaoImpl
				.selectEntitys(DBRuleList.getInstance().add(new DBRule("PROJECTID", projectid, "=")).toList());
		List<Tasklink> tasklinks = tasklinkDaoImpl
				.selectEntitys(DBRuleList.getInstance().add(new DBRule("PROJECTID", projectid, "=")).toList());
		List<Configer> configers = new ArrayList<Configer>();
		List<Configerform> configerforms = new ArrayList<Configerform>();
		List<Template> templates = new ArrayList<Template>();
		List<TemplateDir> templateDirs = new ArrayList<TemplateDir>();
		List<TemplateFile> templateFiles = new ArrayList<TemplateFile>();
		for (Tasknode node : tasknodes) {
			if (node.getModel().equals("configer")) {
				Configer configer = configerServiceImpl.getConfigerEntity(node.getRid());
				configers.add(configer);
				configerforms.addAll(configerformDaoImpl.selectEntitys(
						DBRuleList.getInstance().add(new DBRule("CONFIGERID", configer.getId(), "=")).toList()));
			}
			if (node.getModel().equals("template")) {
				Template template = templateServiceImpl.getTemplateEntity(node.getRid());
				templates.add(template);
				templateDirs.addAll(templatedirDaoImpl.selectEntitys(
						DBRuleList.getInstance().add(new DBRule("TEMPLATEID", template.getId(), "=")).toList()));
				templateFiles.addAll(templatefileDaoImpl.selectEntitys(
						DBRuleList.getInstance().add(new DBRule("TEMPLATEID", template.getId(), "=")).toList()));
			}
		}
		json.put("project", project);
		json.put("tasknodes", tasknodes);
		json.put("tasklinks", tasklinks);
		json.put("configers", configers);
		json.put("templates", templates);
		json.put("templateDirs", templateDirs);
		json.put("templateFiles", templateFiles);
		json.put("configerforms", configerforms);
		ObjectMapper mapper = new ObjectMapper();
		try {
			// 将Java对象转换为JSON字符串
			String jsonString = mapper.writeValueAsString(json);
			return jsonString;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	@Transactional
	public String importProjectByJson(String json, LoginUser currentUser) {
		ObjectMapper mapper = new ObjectMapper();
		try {
			String content = TimeTool.getFormatTimeDate("yyyy-MM-dd HH:mm") + "导入";
			Map<String, String> idMap = new HashMap<String, String>();
			Map<String, Object> map = mapper.readValue(json, Map.class);
			// 生成配置集
			{// CBTG_CONFIGER
				List<Map<String, Object>> configers = (List<Map<String, Object>>) map.get("configers");
				for (Map<String, Object> configer : configers) {
					Configer configerBean = new Configer();
					configerBean.setCatalogid("");
					configerBean.setCode((String) configer.get("code"));
					configerBean.setCtime(TimeTool.getTimeDate14());
					configerBean.setCuser(currentUser.getId());
					configerBean.setEtime(TimeTool.getTimeDate14());
					configerBean.setEuser(currentUser.getId());
					configerBean.setModel((String) configer.get("model"));
					configerBean.setName((String) configer.get("name"));
					configerBean.setPcontent(content);
					configerBean.setPstate((String) configer.get("pstate"));
					configerBean = configerDaoImpl.insertEntity(configerBean);
					idMap.put((String) configer.get("id"), configerBean.getId());
				}
			}
			{// CBTG_CONFIGER_FORM
				List<Map<String, Object>> configerforms = (List<Map<String, Object>>) map.get("configerforms");
				for (Map<String, Object> jsonNode : configerforms) {
					Configerform bean = new Configerform();
					bean.setCode((String) jsonNode.get("code"));
					bean.setConfigerid(idMap.get((String) jsonNode.get("configerid")));
					bean.setCtime(TimeTool.getTimeDate14());
					bean.setCuser(currentUser.getId());
					bean.setEnums((String) jsonNode.get("enums"));
					bean.setEtime(TimeTool.getTimeDate14());
					bean.setEuser(currentUser.getId());
					bean.setInnercode((String) jsonNode.get("innercode"));
					bean.setModel((String) jsonNode.get("model"));
					bean.setName((String) jsonNode.get("name"));
					bean.setPcontent((String) jsonNode.get("pcontent"));
					bean.setPstate((String) jsonNode.get("pstate"));
					bean.setSort((int) jsonNode.get("sort"));
					bean.setValid((String) jsonNode.get("valid"));
					bean = configerformDaoImpl.insertEntity(bean);
					idMap.put((String) jsonNode.get("id"), bean.getId());
				}
			}
			// 生成模板集
			{
				{
					// templates
					List<Map<String, Object>> templates = (List<Map<String, Object>>) map.get("templates");
					for (Map<String, Object> jsonNode : templates) {
						Template bean = new Template();
						bean.setCatalogid("");
						bean.setCode((String) jsonNode.get("code"));
						bean.setCtime(TimeTool.getTimeDate14());
						bean.setCuser(currentUser.getId());
						bean.setEtime(TimeTool.getTimeDate14());
						bean.setEuser(currentUser.getId());
						bean.setName((String) jsonNode.get("name"));
						bean.setPcontent(content);
						bean.setPstate((String) jsonNode.get("pstate"));
						bean = templateDaoImpl.insertEntity(bean);
						idMap.put((String) jsonNode.get("id"), bean.getId());
					}
				}
				{
					// CBTG_TEMPLATE_DIR
					List<Map<String, Object>> templateDirs = (List<Map<String, Object>>) map.get("templateDirs");
					Map<String, String> dirIdMap = new HashMap<String, String>();
					for (Map<String, Object> jsonNode : templateDirs) {
						TemplateDir bean = new TemplateDir();
						bean.setCode((String) jsonNode.get("code"));
						bean.setCtime(TimeTool.getTimeDate14());
						bean.setCuser(currentUser.getId());
						bean.setEtime(TimeTool.getTimeDate14());
						bean.setEuser(currentUser.getId());
						bean.setName((String) jsonNode.get("name"));
						bean.setParentid((String) jsonNode.get("parentid"));
						bean.setPcontent((String) jsonNode.get("pcontent"));
						bean.setPstate((String) jsonNode.get("pstate"));
						bean.setSort((int) jsonNode.get("sort"));
						bean.setTemplateid(idMap.get((String) jsonNode.get("templateid")));
						bean.setTreecode((String) jsonNode.get("treecode"));
						bean = templatedirDaoImpl.insertEntity(bean);
						idMap.put((String) jsonNode.get("id"), bean.getId());
						dirIdMap.put((String) jsonNode.get("id"), bean.getId());
					}
					for (String id : dirIdMap.values()) {
						// 转义parentid 和 treecode
						TemplateDir bean = templatedirDaoImpl.getEntity(id);
						if (!bean.getParentid().equals("NONE")) {
							bean.setParentid(idMap.get(bean.getParentid()));
						}
						String treecode = bean.getTreecode();
						List<String> treenodes = FarmStringUtils.splitByCharacterCount(treecode, 32);
						treecode = "";
						for (String node : treenodes) {
							treecode = treecode + dirIdMap.get(node);
						}
						bean.setTreecode(treecode);
						templatedirDaoImpl.editEntity(bean);
					}

				}
				{
					// templateFiles
					List<Map<String, Object>> templateFiles = (List<Map<String, Object>>) map.get("templateFiles");
					for (Map<String, Object> jsonNode : templateFiles) {
						TemplateFile bean = new TemplateFile();
						bean.setCtime(TimeTool.getTimeDate14());
						bean.setCuser(currentUser.getId());
						// NONE
						if (idMap.get((String) jsonNode.get("dirid")) == null) {
							bean.setDirid(((String) jsonNode.get("dirid")));
						} else {
							bean.setDirid(idMap.get((String) jsonNode.get("dirid")));
						}
						bean.setEtime(TimeTool.getTimeDate14());
						bean.setEuser(currentUser.getId());
						bean.setFilename((String) jsonNode.get("filename"));
						bean.setPcontent((String) jsonNode.get("pcontent"));
						bean.setPstate((String) jsonNode.get("pstate"));
						bean.setTemplateid(idMap.get((String) jsonNode.get("templateid")));
						bean.setText((String) jsonNode.get("text"));
						bean = templatefileDaoImpl.insertEntity(bean);
						idMap.put((String) jsonNode.get("id"), bean.getId());
					}
				}
			}
			// 生成项目
			{
				{
					// CBTG_PROJECT project
					Map<String, Object> jsonNode = (Map<String, Object>) map.get("project");
					Project bean = new Project();
					bean.setCatalogid("");
					bean.setCtime(TimeTool.getTimeDate14());
					bean.setCuser(currentUser.getId());
					bean.setEtime(TimeTool.getTimeDate14());
					bean.setEuser(currentUser.getId());
					bean.setName((String) jsonNode.get("name"));
					bean.setPcontent(content);
					bean.setPstate((String) jsonNode.get("pstate"));
					bean = projectDaoImpl.insertEntity(bean);
					idMap.put((String) jsonNode.get("id"), bean.getId());

				}
				{
					// CBTG_PROJECT_TASKNODE tasknodes
					List<Map<String, Object>> tasknodes = (List<Map<String, Object>>) map.get("tasknodes");
					for (Map<String, Object> jsonNode : tasknodes) {
						Tasknode bean = new Tasknode();
						bean.setCtime(TimeTool.getTimeDate14());
						bean.setCuser(currentUser.getId());
						bean.setEtime(TimeTool.getTimeDate14());
						bean.setEuser(currentUser.getId());
						bean.setModel((String) jsonNode.get("model"));
						bean.setPcontent((String) jsonNode.get("pcontent"));
						bean.setProjectid(idMap.get((String) jsonNode.get("projectid")));
						bean.setPstate((String) jsonNode.get("pstate"));
						bean.setRid(idMap.get((String) jsonNode.get("rid")));
						bean = tasknodeDaoImpl.insertEntity(bean);
						idMap.put((String) jsonNode.get("id"), bean.getId());
					}
				}
				{
					// CBTG_PROJECT_TASKLINK tasklinks
					List<Map<String, Object>> tasklinks = (List<Map<String, Object>>) map.get("tasklinks");
					for (Map<String, Object> jsonNode : tasklinks) {
						Tasklink bean = new Tasklink();
						bean.setCtime(TimeTool.getTimeDate14());
						bean.setCuser(currentUser.getId());
						bean.setEtime(TimeTool.getTimeDate14());
						bean.setEuser(currentUser.getId());
						bean.setExpression((String) jsonNode.get("expression"));
						if (bean.getExpression() == null) {
							bean.setExpression("false");
						}
						bean.setPcontent((String) jsonNode.get("pcontent"));
						bean.setProjectid(idMap.get((String) jsonNode.get("projectid")));
						bean.setPstate((String) jsonNode.get("pstate"));
						if (idMap.get((String) jsonNode.get("snodeid")) == null) {
							bean.setSnodeid((String) jsonNode.get("snodeid"));
						} else {
							bean.setSnodeid(idMap.get((String) jsonNode.get("snodeid")));
						}
						if (idMap.get((String) jsonNode.get("tnodeid")) == null) {
							bean.setTnodeid((String) jsonNode.get("tnodeid"));
						} else {
							bean.setTnodeid(idMap.get((String) jsonNode.get("tnodeid")));
						}
						bean = tasklinkDaoImpl.insertEntity(bean);
						idMap.put((String) jsonNode.get("id"), bean.getId());
					}
				}
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return null;
	}

	@Override
	@Transactional
	public void addTaskNode(String projectId, String parentId, FlowModel flowModel, LoginUser currentUser) {
		if (getProjectEntity(projectId) == null) {
			throw new RuntimeException("项目不存在" + projectId);
		}
		Tasknode node = new Tasknode();
		node.setProjectid(projectId);
		node.setModel(TaskAppModel.none.name());
		node = taskNodeServiceImpl.insertTasknodeEntity(node, currentUser);
		// 所有所有节点数量
		int allNodeNum = tasklinkDaoImpl
				.countEntitys(DBRuleList.getInstance().add(new DBRule("projectid", projectId, "=")).toList());
		// 上级节点的子节点
		List<Tasklink> parentSublink = tasklinkDaoImpl
				.selectEntitys(DBRuleList.getInstance().add(new DBRule("SNODEID", parentId, "=")).toList());
		boolean isToEnd = false;
		for (Tasklink link : parentSublink) {
			if (link.getTnodeid().equals("END")) {
				isToEnd = true;
			}
		}
		// 条件添加
		if (!isToEnd && allNodeNum > 0 && flowModel.equals(FlowModel.condition)) {
			Tasklink link1 = new Tasklink();
			link1.setSnodeid(parentId);
			link1.setTnodeid(node.getId());
			link1.setProjectid(projectId);
			taskLinkServiceImpl.insertTasklinkEntity(link1, currentUser);
			Tasklink link2 = new Tasklink();
			link2.setSnodeid(node.getId());
			link2.setTnodeid("END");
			link2.setProjectid(projectId);
			taskLinkServiceImpl.insertTasklinkEntity(link2, currentUser);
		}
		// 顺序添加
		if (isToEnd || flowModel.equals(FlowModel.sequence) || allNodeNum == 0) {

			if (tasklinkDaoImpl.countEntitys(
					DBRuleList.getInstance().add(new DBRule("projectid", projectId, "=")).toList()) == 0) {
				Tasklink link1 = new Tasklink();
				link1.setSnodeid("START");
				link1.setTnodeid(node.getId());
				link1.setProjectid(projectId);
				taskLinkServiceImpl.insertTasklinkEntity(link1, currentUser);
				Tasklink link2 = new Tasklink();
				link2.setSnodeid(node.getId());
				link2.setTnodeid("END");
				link2.setProjectid(projectId);
				taskLinkServiceImpl.insertTasklinkEntity(link2, currentUser);
			} else {
				List<Tasklink> link = tasklinkDaoImpl
						.selectEntitys(DBRuleList.getInstance().add(new DBRule("PROJECTID", projectId, "="))
								.add(new DBRule("SNODEID", parentId, "=")).toList());
				Tasklink dellink = link.get(0);
				tasklinkDaoImpl.deleteEntity(dellink);
				{
					Tasklink link1 = new Tasklink();
					link1.setSnodeid(dellink.getSnodeid());
					link1.setTnodeid(node.getId());
					link1.setProjectid(projectId);
					taskLinkServiceImpl.insertTasklinkEntity(link1, currentUser);
					Tasklink link2 = new Tasklink();
					link2.setSnodeid(node.getId());
					link2.setTnodeid(dellink.getTnodeid());
					link2.setProjectid(projectId);
					taskLinkServiceImpl.insertTasklinkEntity(link2, currentUser);
				}
			}
		}

	}

	@Override
	@Transactional
	public void bandTaskNodeToModel(String projectId, String nodeId, String nodeModel, String nodeAppId,
			LoginUser currentUser) {
		Tasknode node = taskNodeServiceImpl.getTasknodeEntity(nodeId);
		if (node == null) {
			throw new RuntimeException("该项目中未发现节点：" + nodeId);
		}
		if (!node.getProjectid().equals(projectId)) {
			throw new RuntimeException("该项目（" + projectId + "）中未发现节点：" + nodeId);
		}
		node.setModel(nodeModel);
		node.setRid(nodeAppId);
		taskNodeServiceImpl.editTasknodeEntity(node, currentUser);
	}
}
